package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.usian.common.exception.CatchConsumerException;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;

import com.usian.wemedia.config.RabbitmqConfig;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

   @Autowired
   private WmMaterialMapper wmMaterialMapper;

   @Autowired
   private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto wmNewsPageReqDto) {
        // 判断用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser==null){
            CatchConsumerException.catchException(20003, "用户没有登录，不能操作");
        }
        // 判断参数
        if (wmNewsPageReqDto == null) {
            CatchConsumerException.catchException(20003, "参数有误");
        }
        // 分页初始化
        wmNewsPageReqDto.checkParam();
        //封装条件
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 关键字
        lambdaQueryWrapper.like(
                StringUtils.isNotEmpty(wmNewsPageReqDto.getKeyword()),
                WmNews::getTitle, wmNewsPageReqDto.getKeyword()
        );
        // 频道Id
        lambdaQueryWrapper.eq(
                wmNewsPageReqDto.getChannelId() != null,
                WmNews::getChannelId, wmNewsPageReqDto.getChannelId()
        );
        // 状态
        lambdaQueryWrapper.eq(
                wmNewsPageReqDto.getStatus() != null,
                WmNews::getStatus, wmNewsPageReqDto.getStatus()
        );
        // 开始时间
        lambdaQueryWrapper.ge(
                wmNewsPageReqDto.getBeginPubDate() != null,
                WmNews::getCreatedTime, wmNewsPageReqDto.getBeginPubDate()
        );

        // 结束时间
        lambdaQueryWrapper.le(
                wmNewsPageReqDto.getEndPubDate() != null,
                WmNews::getCreatedTime, wmNewsPageReqDto.getEndPubDate()
        );
        lambdaQueryWrapper.eq(
              WmNews::getUserId,wmUser.getId()
        );
        // 排序：
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        //2.分页条件查询
        IPage<WmNews> iPage = this.page(new Page<>(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize()), lambdaQueryWrapper);
        PageResponseResult responseResult = new PageResponseResult(iPage.getCurrent(),iPage.getSize(),iPage.getTotal());
        responseResult.setData(iPage.getRecords());
        return responseResult;
    }


    @Transactional
    @Override
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        //1.检查参数
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            CatchConsumerException.catchException(20003, "保存信息不完成，不能操作");
        }
        // 保存文章数据
        WmNews wmNews = new WmNews();
        //深克隆
        BeanUtils.copyProperties(dto, wmNews);
        if (-1 == dto.getType()) {
            wmNews.setType(null);
        }
        // 洗数据--
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String images = "";
            for (String image : dto.getImages()) {
                images += image + ",";
            }
            wmNews.setImages(images.substring(0, images.length() - 1));
        }
        // 保存或修改数据库
        this.saveWmNews(wmNews, isSubmit);
        // 判断类型
        // 获取 内容（图文内容）
        String content = dto.getContent();
        // 转换成集合  文字和图片
        List<Map> contentList = JSON.parseArray(content, Map.class);
        // 获取所有的素材（图文内容中的图片集合）
        List<String> materials = this.upGetImagesForContentList(contentList);
        if (isSubmit == WmNews.Status.SUBMIT.getCode() && materials.size() != 0) {
            saveRelativeInfoForNR(materials, wmNews);
        }
        if (isSubmit == WmNews.Status.SUBMIT.getCode()) {
            saveRelativeInfoForFM(dto, materials, wmNews);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    //提取图文内容中的图片集合
    private List<String> upGetImagesForContentList(List<Map> contentList) {
        List<String> materials = new ArrayList<>();
        contentList.stream().forEach(x -> {
            if ("image".equals(x.get("type"))) {
                materials.add((String)x.get("value"));
            }
        });
        return materials;
    }

    private void saveRelativeInfoForNR(List<String> materials, WmNews wmNews) {
        saveRelativeInfo(materials, wmNews, (short) 0);
    }

    public void saveRelativeInfoForFM(WmNewsDto dto, List<String> materials, WmNews wmNews) {
        // 保存关系
        List<String> imagesList = dto.getImages();
        if (-1 == dto.getType()) {  //自动
            if (materials != null && materials.size() > 0 && materials.size() <= 2) {
                // 单图
                wmNews.setType((short) 1);
                imagesList = materials.stream().limit(1).collect(Collectors.toList());
            } else if (materials != null && materials.size() > 2) {
                // 三图
                wmNews.setType((short) 3);
                imagesList = materials.stream().limit(3).collect(Collectors.toList());
            } else {
                // 无图
                wmNews.setType((short) 0);
            }
        }
        if (imagesList != null && imagesList.size() > 0) {
            String images = "";
            for (String image : imagesList) {
                images += image + ",";
            }
            if (wmNews.getImages() == null || "".equals( wmNews.getImages())) {
                wmNews.setImages(images.substring(0, images.length() - 1));
            }
            //保存素材关系
            this.saveRelativeInfo(imagesList, wmNews, (short) 1);
        }
        // 修改wmnes
        this.updateById(wmNews);
    }

    private void saveRelativeInfo(List<String> materials, WmNews wmNews, Short type) {
        List<String> materialIds = new ArrayList<>();
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(WmMaterial::getUrl, materials);
        lambdaQueryWrapper.eq(WmMaterial::getUserId, wmNews.getUserId());
        List<WmMaterial> list = wmMaterialMapper.selectList(lambdaQueryWrapper);
        Map<String, Integer> map = list.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        if (list != null && list.size() > 0) {
            for (String url : materials) {
                Integer materialId = map.get(url);
                materialIds.add(String.valueOf(materialId));
            }
        }
        // 保存
        wmMaterialMapper.saveRelationsByContent(materialIds, wmNews.getId(), type);
}

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 保存或者修改
    private void saveWmNews(WmNews wmNews, Short isSubmit) {
        boolean flag = true;
        // 获取用户信息
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
           CatchConsumerException.catchException(20001, "用户没有登录");
        }
        // 草稿  或者 提交
        wmNews.setStatus(isSubmit);
        if (wmNews.getId() != null) {
          /* //修改
            this.updateById(wmNews);
            // 删除关联表数据   文章ID
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
    */    } else {
            //添加
            wmNews.setUserId(wmUser.getId());
            wmNews.setCreatedTime(new Date());
            if (isSubmit == 1) {
                wmNews.setSubmitedTime(new Date());
            }
            wmNews.setEnable((short) 0);
         flag= this.save(wmNews);
        }
        if(isSubmit == 1 && flag){
            //发送自动审核  MQ
            rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_DIRECT_WMNEWSAUTO,"wmnesauto",wmNews.getId());
        }
    }

    /**
     *@description 根据id查询文章
     *@author  秉性哥
     *@params  Integer id
     *@return  ResponseResult
     *@createTime  2022/10/21
     */
    @Override
    public ResponseResult findById(Integer id) {
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CatchConsumerException.catchException(20003,"没有登陆!");
        }
        if (id==null){
            CatchConsumerException.catchException(20003,"参数不合法!");
        }
        WmNews wmNews=getById(id);
         //给url拼接 http
        ArrayList<String> img = new ArrayList<>();
        String[] split = wmNews.getImages().replace(" ","").split(",");
        for (int i = 0; i < split.length; i++) {
            img.add("http://127.0.0.1/8080/"+split[i]);
        }
        String s = img.toString();
        wmNews.setImages(s);
        if (wmNews==null){
            CatchConsumerException.catchException(20003,"数据为空!");
        }
        return ResponseResult.okResult(wmNews);
    }

    /**
     *@description 文章删除
     *@author  秉性哥
     *@params  id
     *@return  com.usian.model.common.dtos.ResponseResult
     *@createTime  2022/10/21
     */
    @Transactional
    @Override
    public ResponseResult delNews(Integer id) {
        if (id == null) {
            CatchConsumerException.catchException(20003, "文章ID有误");
        }
        // 状态和上架信息
        WmNews wmNews = this.getById(id);
        if (wmNews == null) {
            CatchConsumerException.catchException(20003, "当前文章不可用");
        }
        if(wmNews.getStatus() == 9 && wmNews.getEnable() == 1){
            CatchConsumerException.catchException(20003, "当前文章上架状态，不可删除");
        }
        removeById(wmNews.getId());
        // 删除引用信息
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        return  ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     *@description 文章上下架
     *@author  秉性哥
     *@params   WmNewsDto dto
     *@return  ResponseResult
     *@createTime  2022/10/21
     */
    public ResponseResult downOrUp(WmNewsDto dto) {
        if(dto == null ){
            CatchConsumerException.catchException(20003, "参数不合法");
        }
        if(dto.getId() == null || dto.getEnable()==null){
            CatchConsumerException.catchException(20003, "参数不合法");
        }
        if(dto.getEnable()>1 || dto.getEnable()<0){
            CatchConsumerException.catchException(20003, "上下架操作失败");
        }
        //先查询
        WmNews wmNews =  this.getById(dto.getId());
        if(wmNews == null ){
            CatchConsumerException.catchException(20003, "参数不合法");
        }
        if(wmNews.getStatus() != 9){
            CatchConsumerException.catchException(20003, "文章尚未审核，不能进行上下架操作");
        }
        wmNews.setEnable(dto.getEnable());
        this.updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
